import React, { Component } from 'react';
import { StyleSheet, View, Text, Image, Animated, TouchableOpacity, Alert, FlatList } from 'react-native';
import { NavigationEvents } from 'react-navigation';
import navigationSeevice from '../../../../../../components/navigation/navigationSeevice';
import { GLOBAL } from '../../../../../../config/global';
import { style } from '../../../../../../theme/style';
import ToastUtil from '../../../../../../utils/toast';
import HTTP from '../../../../../../utils/http';
import { API, API_GENERATE } from '../../../../../../config/api';
import { orderStyle, commonStyle } from '../../_common/style';
import { AddressCpt } from './AddressCpt';

const scale = GLOBAL.SCALE;
export class AddressBockCpt extends Component {
	constructor(props) {
		super(props);
		let { visible, listData } = props.data || {};
		let { companyId, companyName } = props.baseData || {};
		this.state = {
			visible,
			startHeight: 0,
			imgObj: new Animated.Value(1),
			rows: listData && listData.rows || [],
			modalVisible: false
		}
		this.onOff = true;

		this.companyId = companyId || '';
		this.companyName = companyName || '';
		this.totalPage = listData && listData.totalPage || 0;
		this.params = {
			isPage: 0,
			pageNo: 1,
			bizType: 'COMPANY_ADDRESS_INFO',
			companyId: this.companyId,
		};
	}

	// 动画
	_startAnimated = () => {
		let { isHeight, startHeight, heightObj, imgObj } = this.state;
		if (isHeight) {
			Animated.timing(imgObj, { toValue: 0, duration: 200, }).start()
			Animated.timing(heightObj, { toValue: startHeight, duration: 300, }).start(() => { this.setState({ isHeight: !isHeight }) });
		} else {
			Animated.timing(imgObj, { toValue: 1, duration: 200, }).start()
			Animated.timing(heightObj, { toValue: 0, duration: 300 }).start(() => { this.setState({ isHeight: !isHeight }) })
		}
	}

	_onLayout = (event) => {
		let { data } = this.props || {};
		let { listData, title } = data || {};
		let startHeight = 0;
		startHeight = listData && listData.rows.length > 3 ? 240 * scale : event.nativeEvent.layout.height;

		if (this.onOff) {
			this.setState({
				startHeight,
				heightObj: new Animated.Value(0),
				isHeight: true,
			})
			this.onOff = false
		}
	}

	//正式表详情（我的客户）
	async getDetail() {
		const { baseData } = this.props;
		const { status, id, choice } = baseData || {};
		let responseData;
		this.params.corpId = choice.corpId;
		if (status) {
			//正式表正的客户详情
			responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_DETAIL), this.params);
		} else {
			//审核的详情
			this.params.id = id;
			responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_APPLY_DETAIL), this.params);
		}
		this.totalPage = responseData.addressListPage && responseData.addressListPage.totalPage;
		let length = responseData.addressListPage && responseData.addressListPage.rows && responseData.addressListPage.rows.length;
		let numHeight = length ? (length > 3 ? 240 * scale : 100 * scale) : 30 * scale;
		this.setState({
			rows: this.params.pageNo == 1 ? responseData.addressListPage && responseData.addressListPage.rows : this.state.rows.concat(responseData.addressListPage.rows),
			heightObj: new Animated.Value(numHeight),
		})
	}

	//刷新列表
	_onAddressRefresh = () => {
		this.params.pageNo = 1;
		this.getDetail();
	}

	//加载列表
	_onAddressEndReached = () => {
		if (this.totaAddresslPage > this.params.pageNo) {
			this.params.pageNo++;
			this.getDetail();
		}
	}

	// 新增
	_addPress() {
		const { baseData } = this.props;
		const { choice } = baseData || {};
		navigationSeevice.navigate('EnterpriseEditAddressPage', {
			companyAddress: {
				companyId: this.companyId,
			},
			companyName: this.companyName,
			choice
		})
	}

	// 删除
	_delPress = (addrId) => {
		Alert.alert('提示', '是否确认删除？', [
			{ text: '取消' },
			{
				text: '确定', onPress: async () => {
					const response = await HTTP.POST(API_GENERATE(API.DEL_COMPANY_ADDRESS), { addrId })
					if (response) {
						ToastUtil.showSuccess('删除成功！');
						this._onAddressRefresh(); //刷新数据
					} else {
						ToastUtil.showError('删除失败，再试试！')
					}
				}
			},
		]);
	}

	// 出入库地址
	_renderAddressItemView = (sendData) => {
		const { baseData } = this.props;
		const { ifEdit, choice } = baseData || {};
		let { provinceName, cityName, areaName, companyName, addrId } = sendData.item || {};
		return (
			<AddressCpt data={sendData.item} key={sendData.index} index={sendData.index}
				length={this.state.rows.length} ifEdit={ifEdit}
				editPress={() => {
					navigationSeevice.navigate('EnterpriseEditAddressPage', {
						companyAddress: sendData.item,
						areaText: (provinceName || '') + (cityName || '') + (areaName || ''),
						companyName: companyName,
						choice
					});
				}}
				delPress={() => { this._delPress(addrId) }} />
		)
	}

	render() {
		let { data, titleStyle, onTitlePress, titleIcon, baseData, oncloseFlatListFn } = this.props || {};
		let { title } = data || {};
		let { ifEdit } = baseData || {};
		let titleImgObj = require('../../../../../../imgs/global/down.png');
		let { heightObj, imgObj, isHeight } = this.state;
		let { rows } = this.state;
		console.log('isHeight', isHeight, ifEdit)
		const spin = imgObj.interpolate({
			inputRange: [0, 1],//输入值
			outputRange: ['0deg', '-90deg'] //输出值
		})
		return (
			<View style={orderStyle.block}>
				<NavigationEvents
					onWillFocus={({ action }) => {
						this.setState({ isHeight: true }, () => {
							this._startAnimated();
							this._onAddressRefresh();
						})
					}}
				/>
				<TouchableOpacity activeOpacity={1} onPress={this._startAnimated} style={[{ padding: 5 * scale }, commonStyle.row2]}>
					<View style={{ flexDirection: 'row', alignItems: 'center' }}>
						<Text style={[commonStyle.fontTitle, titleStyle]} onPress={() => onTitlePress && onTitlePress()}>{title}</Text>
						{titleIcon ? <Image source={titleIcon} style={{ marginLeft: 10 * scale }} /> : null}
						{!isHeight && ifEdit ? <Text style={[styles.addText, styles.border]} onPress={() => this._addPress()}>新增/管理地址</Text> : null}
					</View>
					<View style={styles.imgBox}>
						<Animated.Image style={[styles.imgStyle, { transform: [{ rotate: spin }] }]} source={titleImgObj}></Animated.Image>
					</View>
				</TouchableOpacity>
				<Animated.View style={{ height: heightObj, overflow: 'hidden' }}>
					<View ref='zy' onLayout={(event) => this._onLayout(event)} style={[styles.body]} onStartShouldSetResponderCapture={() => { oncloseFlatListFn && oncloseFlatListFn() }}>
						{
							rows && rows.length ?
								<FlatList
									data={rows}
									renderItem={this._renderAddressItemView.bind(this)}
									onEndReachedThreshold={1}
									onEndReached={() => { this._onAddressEndReached() }}
									onRefresh={() => { this._onAddressRefresh() }}
									refreshing={false}
								/>
								: (<Text style={{ fontSize: 10 * scale }}>暂未提交该类数据</Text>)
						}
					</View>
				</Animated.View>
			</View>
		)
	}
}

const styles = StyleSheet.create({
	imgBox: {
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 5 * scale,
		paddingRight: 5 * scale
	},
	imgStyle: {
		tintColor: '#D8D8D8',
		width: 10 * scale,
		height: 6 * scale
	},
	body: {
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
	},
	bockCptTitleStyle: {
		fontSize: 12 * scale
	},
	addText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		marginLeft: 12 * scale
	},
	border: {
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderWidth: 1 * scale,
		borderRadius: 7 * scale,
		padding: 5 * scale
	}

})